package com.lekang.le.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lekang.common.annotation.Anonymous;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.le.domain.WxUserBinding;
import com.lekang.le.service.IWxUserBindingService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 微信用户绑定老人Controller
 * 
 * @author lekang
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/le/wx/binding")
@CrossOrigin
public class WxUserBindingController extends BaseController
{
    @Autowired
    private IWxUserBindingService wxUserBindingService;

    /**
     * 查询微信用户绑定老人列表
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('le:binding:list')")
    @GetMapping("/list")
    public TableDataInfo list(WxUserBinding wxUserBinding)
    {
        startPage();
        List<WxUserBinding> list = wxUserBindingService.selectWxUserBindingList(wxUserBinding);
        return getDataTable(list);
    }

    /**
     * 导出微信用户绑定老人列表
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('le:binding:export')")
    @Log(title = "微信用户绑定老人", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WxUserBinding wxUserBinding)
    {
        List<WxUserBinding> list = wxUserBindingService.selectWxUserBindingList(wxUserBinding);
        ExcelUtil<WxUserBinding> util = new ExcelUtil<WxUserBinding>(WxUserBinding.class);
        util.exportExcel(response, list, "微信用户绑定老人数据");
    }

    /**
     * 获取微信用户绑定老人详细信息
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('le:binding:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wxUserBindingService.selectWxUserBindingById(id));
    }

    /**
     * 新增微信用户绑定老人
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('le:binding:add')")
    @Log(title = "微信用户绑定老人", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WxUserBinding wxUserBinding)
    {
        return toAjax(wxUserBindingService.insertWxUserBinding(wxUserBinding));
    }

    /**
     * 修改微信用户绑定老人
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('le:binding:edit')")
    @Log(title = "微信用户绑定老人", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WxUserBinding wxUserBinding)
    {
        return toAjax(wxUserBindingService.updateWxUserBinding(wxUserBinding));
    }

    /**
     * 删除微信用户绑定老人
     */
    @Anonymous
//    @PreAuthorize("@ss.hasPermi('le:binding:remove')")
    @Log(title = "微信用户绑定老人", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wxUserBindingService.deleteWxUserBindingByIds(ids));
    }

    /**
     * 小程序绑定家人接口
     * 
     * @param wxUserId 微信用户ID（从请求头或参数获取）
     * @param familyName 家人姓名
     * @param idCard 身份证号
     * @param relationship 称呼关系
     * @return 绑定结果
     */
    @Anonymous
    @PostMapping("/bind")
    public AjaxResult bindFamily(
            @RequestParam Long wxUserId,
            @RequestParam String familyName,
            @RequestParam String idCard,
            @RequestParam String relationship)
    {
        try {
            String result = wxUserBindingService.bindFamily(wxUserId, familyName, idCard, relationship);
            
            if ("绑定成功".equals(result)) {
                return success(result);
            } else {
                return error(result);
            }
        } catch (Exception e) {
            logger.error("绑定家人失败", e);
            return error("绑定失败，系统异常");
        }
    }

    /**
     * 根据微信用户ID查询绑定的老人列表
     * 
     * @param wxUserId 微信用户ID
     * @return 绑定关系列表
     */
    @Anonymous
    @GetMapping("/list/family")
    public AjaxResult getFamilyList(@RequestParam Long wxUserId)
    {
        try {
            List<WxUserBinding> list = wxUserBindingService.selectByWxUserId(wxUserId);
            return success(list);
        } catch (Exception e) {
            logger.error("查询家人列表失败", e);
            return error("查询失败，系统异常");
        }
    }

    /**
     * 解绑家人（小程序端使用）
     * 只删除wx_user_binding表的记录，不影响老人和家属的实际关系
     * 
     * @param bindingId 绑定关系ID（wx_user_binding表的主键）
     * @param wxUserId 微信用户ID（用于安全验证）
     * @return 结果
     */
    @Anonymous
    @PostMapping("/unbind")
    public AjaxResult unbindFamily(
            @RequestParam(value = "bindingId", required = true) Long bindingId,
            @RequestParam(value = "wxUserId", required = true) Long wxUserId)
    {
        try {
            int result = wxUserBindingService.unbindFamily(bindingId, wxUserId);
            if (result > 0) {
                return success("解绑成功");
            } else {
                return error("解绑失败，绑定关系不存在或无权限");
            }
        } catch (Exception e) {
            logger.error("解绑家人失败", e);
            return error("解绑失败，系统异常");
        }
    }
}
